package com.heima.wemedia.filter;

import com.heima.model.common.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.pojos.WmUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "wmTokenFilter",urlPatterns = "/*")
@Slf4j
@Component
public class WmTokenFilter extends GenericFilterBean {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //获取请求对象
        HttpServletRequest request=(HttpServletRequest)servletRequest;
        //得到header中的信息
        String useId = request.getHeader("userId");
        if (useId != null){
            WmUser user = new WmUser();
            user.setId(Integer.valueOf(useId));
            // 保存到当前线程中
            WmThreadLocalUtils.setUser(user);
        }
        // 如果没有则直接放行
        filterChain.doFilter(servletRequest,servletResponse);
    }
}
